package com.haiheng.common.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.PowerManager
import android.text.format.DateUtils
import android.util.Log
import com.haiheng.common.bean.ScheduledTaskJob
import com.haiheng.common.bean.ScheduledTaskParas
import com.haiheng.common.bean.ScheduledTasksBean
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.ys.rkapi.MyManager
import java.text.SimpleDateFormat
import java.util.*
import kotlin.system.measureTimeMillis
import androidx.core.content.ContextCompat.getSystemService
import com.haiheng.common.constant.AppConstant
import com.haiheng.library_base.toast.GsonUtils
import com.haiheng.library_base.utils.SPUtils


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/5/6 0006
 * @Version: 1.0
 */
object PowerOnOffHelper {


    /**
     * 设置关机或者重启（分为触沃屏和雍慧广告屏）
     * 命令类型 TurnOn=1(开机)、TurnOff=2(关机)、Reboot=3(重启)、Lockscreen=4(锁屏)、TurnOnTheInBookPartition=11(打开书柜分区)
     */
    fun setShutdownOrReboot(context: Context, tasksBean: ScheduledTasksBean): Boolean {

        if (tasksBean.commandName.equals("TurnOff")) {
            //关机
            shutdownByChuWo(context)
            shutdowByYongHui(context)
        } else if (tasksBean.commandName.equals("Reboot")) {
            //重启
            rebootByChuWo(context)
            rebootByYongHui(context)
        } else if (tasksBean.commandName.equals("TurnOn")) {

        }

        return false
    }


    fun shutdownByChuWo(context: Context) {
        //关机
        val manager = MyManager.getInstance(context)
        manager.shutdown()
    }

    fun rebootByChuWo(context: Context) {
        //重启
        val manager = MyManager.getInstance(context)
        manager.reboot()
    }

    fun shutdowByYongHui(context: Context) {
        val now = Calendar.getInstance()
        var trunOnTask = getTurnOnTask(context)
        if (trunOnTask != null){
            val intent = Intent("android.intent.action.setpoweronoff")
            val timeoffArray = getDateArray(now)
            val timeonArray =  getDateArray(getScheduledTime(trunOnTask))
            intent.putExtra("timeon", timeonArray)
            intent.putExtra("timeoff", timeoffArray)
            intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
            context.sendBroadcast(intent)
            LogWriter.d("雍慧屏设置关机 timeonArray ：${timeonArray.contentToString()}  timeoffArray:${timeoffArray.contentToString()}")
        }

    }


    fun rebootByYongHui(context: Context) {
        val intent: Intent = Intent("com.android.yf_reboot")
        intent.putExtra("reboot_time", 3)
        context.sendBroadcast(intent)
    }


    fun setPowerOnOff(context: Context, tasksBean: ScheduledTasksBean): Boolean {
        if (tasksBean != null && tasksBean.services != null
            && tasksBean.services.size > 0 && tasksBean.services.get(0).properties != null
            && tasksBean.services.get(0).properties.size > 0
            && tasksBean.services.get(0).properties.get(0).content != null
            && tasksBean.services.get(0).properties.get(0).content.jobList != null
            && tasksBean.services.get(0).properties.get(0).content.jobList.size > 0
        ) {
            var jobList = tasksBean.services.get(0).properties.get(0).content.jobList
            var timeOnPars: ScheduledTaskParas? = null
            var timeOffPars: ScheduledTaskParas? = null
            var timeOnTask: ScheduledTaskJob? = null
            var timeOffTask: ScheduledTaskJob? = null
            for (task in jobList) {
                when (task.jobName) {
                    "TurnOn" -> {
                        timeOnPars = task.paras
                        timeOnTask = task
                    }
                    "TurnOff" -> {
                        timeOffPars = task.paras
                        timeOffTask = task
                    }
                }
            }
            if (timeOffPars != null && timeOnPars != null) {
                var timeonArray =
                    timeOnPars.minutes?.get(0)?.let { intArrayOf(timeOnPars.hours[0], it) }
                var timeoffArray =
                    timeOffPars.minutes?.get(0)?.let { intArrayOf(timeOffPars.hours[0], it) }
                var weekdays = intArrayOf(
                    if (timeOffPars.weeks.contains(1)) 1 else 0,
                    if (timeOffPars.weeks.contains(2)) 1 else 0,
                    if (timeOffPars.weeks.contains(3)) 1 else 0,
                    if (timeOffPars.weeks.contains(4)) 1 else 0,
                    if (timeOffPars.weeks.contains(5)) 1 else 0,
                    if (timeOffPars.weeks.contains(6)) 1 else 0,
                    if (timeOffPars.weeks.contains(7)) 1 else 0
                )
                var result =
                    setPowerOnOffWithWeeklyByChuwo(context, timeonArray, timeoffArray, weekdays)
                if (timeOnTask != null && timeOffTask != null) {
                    setPowerOnOffYongHui(context, timeOnTask, timeOffTask)
                }
                return result
            }
        }
        return false
    }

    fun setPowerOnOffWithWeeklyByChuwo(
        context: Context, powerOnTime: IntArray?,
        powerOffTime: IntArray?,
        weekdays: IntArray?
    ): Boolean {
        LogUtils.d("设置触沃开关机时间timeonArray ：${powerOnTime.contentToString()}  timeoffArray:${powerOffTime.contentToString()} weekdays:${weekdays.contentToString()}")
        //此方法一天只能有一组时间设入，并且开机时间在前，关机时间在后
        val manager = MyManager.getInstance(context)
//        var powerOnTime = intArrayOf(8,30)
//        var powerOffTime = intArrayOf(18,30)
//        var weekdays = intArrayOf(1,1,1,1,1,0,0);//周一到周日工作状态,1为开机，0为不开机
//        设置上述时间将会在每周一到周五的8:30开机，18:30关机。
        var result = manager.setPowerOnOffWithWeekly(powerOnTime, powerOffTime, weekdays);
        LogWriter.e("设置周模式的定时开关机：$result")
        return result
//        return false
    }

    fun setPowerOnOffByChuwo(context: Context, taskParas: ScheduledTaskParas) {
        //触沃广告屏 设置开关机
        val manager = MyManager.getInstance(context)
        //开机时间，年月日时分
        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
        var result = manager.setPowerOnOff(timeonArray, timeoffArray)
    }

    fun setPowerOnOffYongHui(context: Context, taskParas: ScheduledTaskParas) {
        val intent = Intent("android.intent.action.setpoweronoff")
        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
        intent.putExtra("timeon", timeonArray)
        intent.putExtra("timeoff", timeoffArray)
        intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
        context.sendBroadcast(intent)

    }


    fun setPowerOnOffYongHui(
        context: Context,
        timeOnTask: ScheduledTaskJob,
        timeOffTask: ScheduledTaskJob
    ) {
        //65寸广告屏开关机
        // 下一次开机时间
        val nextTimeOnlendar = getScheduledTime(timeOnTask)
        LogUtils.e("下一次开机时间为：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextTimeOnlendar.time))
        // 下一次关机时间
        val nextShutdowmCalendar = getScheduledTime(timeOffTask)
        LogUtils.e("下一次关机时间为：" + SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextShutdowmCalendar.time))
        val timeonArray = getDateArray(nextTimeOnlendar)
        val timeoffArray = getDateArray(nextShutdowmCalendar)
        //65寸广告屏开关机
        val intent = Intent("android.intent.action.setpoweronoff")
//        val timeoffArray = intArrayOf(2023, 4, 24, 17, 23)
//        val timeonArray = intArrayOf(2023, 4, 24, 17, 30)
        intent.putExtra("timeon", timeonArray)
        intent.putExtra("timeoff", timeoffArray)
        intent.putExtra("enable", true) //使能开关机功能，设为 false,则为关闭
        context.sendBroadcast(intent)
        LogWriter.d("雍慧屏设置开关机时间 timeonArray ：${timeonArray.contentToString()}  timeoffArray:${timeoffArray.contentToString()}")

    }

    fun getDateArray(calendar: Calendar): IntArray {
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1  // 月份从0开始，需要加1
        val day = calendar.get(Calendar.DAY_OF_MONTH)
        val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        val second = calendar.get(Calendar.SECOND)
        return intArrayOf(year, month, day, hourOfDay, minute)
    }

    fun getNextScheduledTime(cronExpression: String, currentTime: Long): Long {
        // "cron":"0 17 18 ? * 2,5,6",
        val cronParams = cronExpression.split(" ")
        val calendar = Calendar.getInstance().apply { timeInMillis = currentTime }

        // 解析 cron 表达式中的星号，包括年份（默认为今年）
        val year = calendar.get(Calendar.YEAR)
        val cronYear =
            if (cronParams.size > 6 && cronParams[6] != "?") cronParams[6] else year.toString()

        // 解析 cron 表达式中的时间参数
        val cronMinute = cronParams[1].toInt()
        val cronHour = cronParams[2].toInt()

        // 解析 cron 表达式中的星期参数
        val cronWeek = cronParams[5]
        val weekdays = if (cronWeek == "?") null else cronWeek.split(",").map { it.toInt() }

        // 计算下一个定时时间
        while (true) {
            calendar.apply {
                add(Calendar.DAY_OF_MONTH, 1) // 每次加一天
                set(Calendar.HOUR_OF_DAY, cronHour)
                set(Calendar.MINUTE, cronMinute)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }

            // 判断是否符合星期要求
            if (weekdays == null || weekdays.contains(calendar.get(Calendar.DAY_OF_WEEK))) {
                val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                val scheduledTime = dateFormat.parse(
                    "$cronYear-${calendar.get(Calendar.MONTH) + 1}-${
                        calendar.get(Calendar.DAY_OF_MONTH)
                    } ${cronHour}:${cronMinute}:00"
                )!!.time
                if (scheduledTime > currentTime) {
                    return scheduledTime
                }
            }
        }
    }


    fun getScheduledTime(taskParas: ScheduledTaskJob): Calendar {
        val shutdownTime = parseShutdownTime(taskParas) // 解析关机时间

        val now = Calendar.getInstance()
        val shutdownToday = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, shutdownTime.get(Calendar.HOUR_OF_DAY))
            set(Calendar.MINUTE, shutdownTime.get(Calendar.MINUTE))
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }

        if (shutdownToday.before(now)) { // 关机时间已经过了，则返回下一次开关机时间
//            shutdownToday.add(Calendar.DAY_OF_MONTH, 1)
            return Calendar.getInstance().apply {
                timeInMillis = getNextScheduledTime(taskParas.cron,System.currentTimeMillis())
            }
        }else {
            //如果时间点没过，如果是当日星期，则返回今天时间，如果不符合当前星期，也返回下一次关机时间
            val cronParams = taskParas.cron.split(" ")
            // 解析 cron 表达式中的星期参数
            val cronWeek = cronParams[5]
            val weekdays = if (cronWeek == "?") null else cronWeek.split(",").map { it.toInt() }
            if (weekdays == null || weekdays.contains(shutdownToday.get(Calendar.DAY_OF_WEEK))) {
                return  shutdownToday
            }else{
                return Calendar.getInstance().apply {
                    timeInMillis = getNextScheduledTime(taskParas.cron,System.currentTimeMillis())
                }
            }
        }

        return shutdownToday
    }

    private fun parseShutdownTime(taskParas: ScheduledTaskJob): Calendar {
        val paras = taskParas.paras ?: return Calendar.getInstance()

        val hours = paras.hours?.getOrNull(0) ?: return Calendar.getInstance()
        val minutes = paras.minutes?.getOrNull(0) ?: return Calendar.getInstance()

        val shutdownTime = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, hours)
            set(Calendar.MINUTE, minutes)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        return shutdownTime
    }


    fun getTurnOnTask(context: Context):ScheduledTaskJob? {
        var taskString = SPUtils.getInstance().getString(AppConstant.SP_SCHEDULED_TASK)
        var timeOnTask: ScheduledTaskJob? = null
        var timeOffTask: ScheduledTaskJob? = null
        if (taskString.isNotBlank()){
            try {
                var tasksBean = GsonUtils.fromJson(taskString, ScheduledTasksBean::class.java)
                if (tasksBean != null && tasksBean.services != null
                    && tasksBean.services.size > 0 && tasksBean.services.get(0).properties != null
                    && tasksBean.services.get(0).properties.size > 0
                    && tasksBean.services.get(0).properties.get(0).content != null
                    && tasksBean.services.get(0).properties.get(0).content.jobList != null
                    && tasksBean.services.get(0).properties.get(0).content.jobList.size > 0
                ) {
                    var jobList = tasksBean.services.get(0).properties.get(0).content.jobList
                    for (task in jobList) {
                        when (task.jobName) {
                            "TurnOn" -> {
                                timeOnTask = task
                            }
                            "TurnOff" -> {
                                timeOffTask = task
                            }
                        }
                    }
                }
            }catch (ex:Exception){
                LogWriter.e("getTurnOffTask 定时任务解析异常:${ex.message}")
            }
        }
        return  timeOnTask
    }

}